import { login, logout, getInfo, GetToken, MyAuth } from '@/api/sys'
import { GetEnum } from '@/api/ctrls'
import { getToken, setToken, removeToken, setEnumList } from '@/utils/auth.js'
import router, { resetRouter } from '@/router'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  enumList: {} // 枚举列表
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ENUMLIST: (state, enumList) => {
    state.enumList = enumList
    setEnumList(enumList)
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { success, code, msg } = await login({ ...userInfo })
    setToken(code)
    commit('SET_TOKEN', code)
    if (success) {
      const res = await GetEnum()
      commit('SET_ENUMLIST', res.data)
    }
    return { success, msg }
  },
  async GetToken({ commit }) {
    try {
      const { data } = await GetToken()
      setToken(data)
      commit('SET_TOKEN', data)
      return true
    } catch (e) {
      return false
    }
  },
  // get user info
  async getMyAuth({ commit, state }) {
    try {
      const info = await getInfo()
      const { ctime, username, headpicurl } = info
      commit('SET_NAME', username)
      commit('SET_AVATAR', headpicurl)
      commit('SET_INTRODUCTION', ctime)
      const { success, msg, list } = await MyAuth()
      if (success) {
        commit('SET_ROLES', list)
        return list
      } else {
        Message.error(msg)
        commit('SET_ROLES', [])
        return []
      }
    } catch (e) {
      return []
      console.log(e)
      // TODO handle the exception
    }
  },
  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    console.log('resetToken==========>')
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
